<template>
  <div class="content">
    <t-loading text="加载中..." :loading="!showFlag" size="small" show-overlay style="height: 100%;width: 100%">
    <TopAudioBox :audioArray="audioArray" :audioSrc="audioSrc" :templateStatus="templateStatus"></TopAudioBox>
    <div class="bodyBox">
      <div class="left">
        <!--        录音信息、对话内容-->
        <AudioDialogue
            :dialogueData="dialogueData"
            @getDetailData="getDetailData"
        ></AudioDialogue>
      </div>
      <div class="right">
        <!--        质检情况-->
        <QualitySituation
        ></QualitySituation>
      </div>
    </div>
    <div class="footerBox">
      <t-button variant="outline" class="backBtn" @click="handleBack">
        <template #icon>
          <svg-icon
              :name="'icon-bottomBack'"
          ></svg-icon>
        </template>
        返回
      </t-button>
      <t-button v-if="store.resultType !== 2" class="hoverBlue" variant="outline" @click="handleResetQuality" v-permission="['result:reload']" :disabled="templateStatus === 1">
        <template #icon>
          <svg-icon
              :name="'icon-bottomReset'"
          ></svg-icon>
        </template>
        重新质检
      </t-button>
      <t-button class="hoverBlue" variant="outline" @click="handleSave" v-permission="['result:update']" :disabled="templateStatus === 1">
        <template #icon>
          <svg-icon
              :name="'icon-bottomSave'"
          ></svg-icon>
        </template>
        保存
      </t-button>
      <t-button variant="outline" class="previousBtn hoverBlue" v-if="isShowPreviousBtn" @click="handlePrevious">
        <template #icon>
          <svg-icon
              :name="'icon-bottomNext'"
          ></svg-icon>
        </template>
        上一通
      </t-button>

      <t-button variant="outline" class="nextBtn hoverBlue" v-if="isShowNextBtn" @click="handleNext">
        <template #icon>
          <svg-icon
              :name="'icon-bottomNext'"
          ></svg-icon>
        </template>
        下一通
      </t-button>
    </div>
    </t-loading>
    <!--    重新质检弹窗-->
    <ResetQualityDialog
        :resetVisible="resetVisible"
        :qualityIdList="qualityIdList"
        @closeResetDialog="closeResetDialog"
    ></ResetQualityDialog>
  </div>
</template>

<script setup>
import TopAudioBox from './components/topAudioBox.vue'
import AudioDialogue from './components/audioDialogue.vue'
import QualitySituation from './components/qualitySituation.vue'
import ResetQualityDialog from './components/resetQualityDialog.vue'

import {computed, nextTick, onMounted, provide, reactive, ref, toRaw, watch} from 'vue'
import {useRoute, useRouter} from "vue-router";
import {qualityDetail, editQuality} from "../../api/qualityResult";
import { usePageStore } from '@/pinia/page.js'
const store = usePageStore()

import { isEqual, sortBy } from "lodash"

const router = useRouter()
const route = useRoute()

const showFlag = ref(false)
provide('showFlag', showFlag)
// onMounted(() => {
//   getDetailData()
// })
// 原始数据
const originalScoreData = ref([])
const originalSuggestions = ref('')
// 获取详情数据
const templateScore = ref({}) // 质检评分
provide('templateScore', templateScore)
const tagInfo = ref({}) // 标签信息
provide('tagInfo', tagInfo)
const infoIds = ref({}) // id信息
provide('infoIds', infoIds)
const historyInfo = ref([]) // 评分历史
provide('historyInfo', historyInfo)
const templateName = ref('') // 质检模版名称
provide('templateName', templateName)
const suggestions = ref('') // 评语和建议
provide('suggestions', suggestions)

const dialogueData = reactive({}) // 对话内容

const audioArray = ref([])
const audioSrc = ref('')

let templateStatus = ref(0)

const getDetailData = () => {
  templateStatus = store.templateStatus
  showFlag.value = false
  let id = store.currentDetailId
  qualityDetail(id).then(res => {
    templateScore.value = {} // 重置评分数据
    dialogueData.value = {} // 重置对话内容数据
    if(res.code === 0) {
      Object.assign(dialogueData, res.data)
      templateScore.value = res.data['templateScore']
      originalScoreData.value = JSON.parse(JSON.stringify(res.data['templateScore']))
      tagInfo.value = res.data['recordingTemplateTags']
      infoIds.value = {
        asrId: res.data.asrId,
        templateId: res.data.templateId
      }
      historyInfo.value = res.data['templateScoreList']
      templateName.value = res.data['templateScore'].name
      suggestions.value = res.data.remark ? res.data.remark : ''
      originalSuggestions.value = JSON.parse(JSON.stringify(suggestions.value))
      console.log('打印res', res);
      // Object.assign(audioArray, res.data.recordingDetail.recordingByte)
      audioArray.value = res.data.recordingDetail.recordingByte
      audioSrc.value = res.data.recordingDetail.recording
      showFlag.value = true
    }
  })
}
provide('getDetailData', getDetailData)
// 返回
const handleBack = () => {
  // ['智能质检结果', '标签质检结果', '人工质检结果']
  let backAry = ['resultAi', 'resultLabel', 'resultArt']
  router.push(`/qualityResult/${backAry[store.resultType]}`)
}
// 重新质检
const resetVisible = ref(false)
const qualityIdList = ref([])
const handleResetQuality = () => {
  qualityIdList.value = [ store.currentDetailId ]
  resetVisible.value = true
}
// 质检弹窗关闭
const closeResetDialog = (flag) => {
  resetVisible.value = false
  if(flag) {
    store.$patch({ isResetQuality: true })
    getDetailData()
  }
}
// 保存
const handleSave = () => {
  // 判断评语和建议是否变化
  // console.log('suggestions', suggestions.value === originalSuggestions.value)
  // 质检评分是否手动变化
  console.log(JSON.stringify(originalScoreData.value) === JSON.stringify(templateScore.value))
  let isScoreChange = JSON.stringify(originalScoreData.value) === JSON.stringify(templateScore.value)

  // 标签信息是否变化
  let tagData = toRaw(store.itemTagsData)
  // let ary = sortBy([ ...tagData.customTags, ...tagData.seatsTags ], function (o) {
  //   return o.tagId;
  // });
  // let ary1 = sortBy(toRaw(tagInfo.value), function (e) {
  //   return e.tagId
  // })
  // console.log('isEqual', isEqual(ary1, ary))

  let data = {
    ...infoIds.value,
    scoreUpdate: isScoreChange ? 0 : 1,
    remark: suggestions.value,
    recordingTemplateTags: [ ...tagData.customTags, ...tagData.seatsTags ],
    templateScoreDTO: templateScore.value
  }

  // 计算得分赋值
  data.templateScoreDTO['score'] = store.calculateScore
  editQuality(data).then(res => {
    if(res.code === 0) {
      getDetailData()
    }
  })
}

const isShowPreviousBtn = ref(true)
const isShowNextBtn = ref(true)

// 上下一通显示
const showBtn = () => {
  let index = store.allIds.findIndex(item => item === store.currentDetailId)
  isShowNextBtn.value = !(store.allIds.length === 1 || ((store.allIds.length - 1) === index));
  isShowPreviousBtn.value = !(store.allIds.length === 1 || index === 0);
  getDetailData()
}
// 上一通
const handlePrevious = () => {
  let index = store.allIds.findIndex(item => item === store.currentDetailId)
  store.$patch({ currentDetailId: store.allIds[index - 1 ] })
  showBtn()
}
// 下一通
const handleNext = () => {
  let index = store.allIds.findIndex(item => item === store.currentDetailId)
  store.$patch({ currentDetailId: store.allIds[index + 1 ] })
  showBtn()
}
onMounted(() => {
  // set left menu light
  usePageStore().$patch((state) => {
    // ['智能质检结果', '标签质检结果', '人工质检结果']
    let backAry = ['resultAi', 'resultLabel', 'resultArt']
    state.lightMenu = `/qualityResult/${backAry[store.resultType]}`
  })
  showBtn()
})
</script>

<style lang="scss" scoped>
.content {
  background-color: #EBECED !important;
  padding: 8px;
  .bodyBox {
    height: calc(100vh - 316px);
    //overflow-y: auto;
    border-radius: 4px;
    //background-color: rgba(255, 255, 255, 1);
    margin: 8px 0;
    display: flex;
    .left {
      flex: 1;
    }
    .right {
      width: 338px;
    }
  }
  .footerBox {
    height: 52px;
    background-color: rgba(255, 255, 255, 1);
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    :deep(.t-button) {
      width: 101px;
      height: 28px;
      background-color: rgba(30, 117, 254, 1);
      margin: 0 7px;
      font-size: 12px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      .svg-icon {
        height: 16px;
        width: 16px;
        margin-right: 5px;
      }
    }
    .backBtn {
      background: rgba(255, 255, 255, 1);
      border: 0.5px solid rgba(12, 13, 14, 1);
      color: rgba(12, 13, 14, 1);
    }
    .nextBtn {
      .svg-icon {
        height: 12px;
        width: 12px;
      }
    }
    .previousBtn {
      .svg-icon {
        height: 12px;
        width: 12px;
        transform: rotate(180deg);
      }
    }
  }
}
</style>
